﻿@model System.Collections.IDictionary
@using Kooboo.Web.Script.Serialization
@{
    Layout = ViewBag.Layout ?? "_TR.cshtml";

    var fullPropertyName = ViewData.TemplateInfo.HtmlFieldPrefix;
    if (ViewBag.FullPropertyName != null)
    {
        fullPropertyName = ViewBag.FullPropertyName.ToString();
    }
    var elementId = fullPropertyName.Replace(".", "_");
    var propertyName = ViewData["name"] == null ? ViewData.ModelMetadata.PropertyName : ViewData["name"].ToString();
    var koTemplateId = elementId + "_Editor";
}

<table class="key-value" id="@koTemplateId">
    <thead data-bind="visible: data().length > 0">
        <tr>
            <th>@("Key".Localize())
            </th>
            <th>@("Value".Localize())
            </th>
        </tr>
    </thead>
    <tbody data-bind="foreach: data">
        <tr>
            <td>
                <input type="text" title='key' name="Key" class="short" data-bind="value: $data.Key, attr: { name: $parent.getPrefixFieldName($index()) + 'Key' }" />
            </td>
            <td>
                <textarea name="Value" data-bind="value: $data.Value, attr: { name: $parent.getPrefixFieldName($index()) + 'Value' }"></textarea>
            </td>
            <td>
                <a class="action" data-bind="click: $parent.removeItem">@Html.IconImage("minus")</a>
            </td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td><a class="action" data-bind="click: $data.addItem">@Html.IconImage("plus")</a></td>
        </tr>
    </tfoot>
</table>
@if (!string.IsNullOrEmpty(ViewData.ModelMetadata.Description))
{
    <em class="tip">@Html.Raw(ViewData.ModelMetadata.Description.Localize())</em>
}
@{
    var modelJson = Model == null ? "[]" : ((Dictionary<string, string>)Model).ToList().ToJSON();
}
<script type="text/javascript">
    $(function () {

        function AppViewModel() {
            var self = this;

            self.data = ko.observableArray(@Html.Raw(modelJson));
            self.data.subscribe(function (newValue) {
                $('textarea').autosize({ className: 'autoresize' });
            });

            self.addItem = function () {
                self.data.push({ Key: '', Value: '' });
                $('textarea').autosize({ className: 'autoresize' });
            };

            self.removeItem = function () {
                self.data.remove(this);
            };

            var namePrfix = '@fullPropertyName';
            self.getPrefixFieldName = function (index) {
                return namePrfix + '[' + (index) + '].';
            };
        }
        var $template = $('#@koTemplateId');
        var model = new AppViewModel()
        $template.data("KO_ViewModel", model);
        ko.applyBindings(model, $template[0]);
        $('textarea').autosize({ className: 'autoresize' });
    });
</script>
